
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>

int ch_width_3 = 0;
int leftPwm = 0;
int rightPwm = 0;
const unsigned long transInterval = 10000; // 发送数据的时间间隔 10秒

Servo ch3;
float battery = 8.4;  //受控端电池电压  


struct Signal {
  byte throttle;
  byte pitch;
  byte roll;
  byte yaw;
  byte aux1;
  bool aux2;
};


Signal data;
const uint64_t pipeIn = 0xE9E8F0F0E1LL;
RF24 radio(9, 10); 


void ResetData(){
  data.throttle = 127;   
  data.pitch = 127;   
  data.roll = 127;    
  data.yaw = 127;     
  data.aux1 = 127;    
  data.aux2 = 0;   
}


void setup(){
  ch3.attach(4);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  ResetData();
//  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1,pipeIn);
  radio.setAutoAck(1, true);
  radio.enableAckPayload();
  radio.setPayloadSize(32);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);
  radio.startListening(); 
}


unsigned long lastRecvTime = 0;
unsigned long lastTransTime = 0;


void recvData(){
  while ( radio.available() ) {
    radio.read(&data, sizeof(Signal));
    lastRecvTime = millis();   
    unsigned long currentMillis = millis();
    if (currentMillis - lastTransTime > transInterval){
      int sent_val = battery * 100;
      radio.writeAckPayload(1, &sent_val, sizeof(sent_val));
      lastTransTime = currentMillis;
    }
  }
}

void loop(){
  recvData();
  unsigned long now = millis();
  if ( now - lastRecvTime > 1000 ) {
    ResetData();
  }
  ch_width_3 = map(data.throttle, 0, 255, 1000, 2000);      
  ch3.writeMicroseconds(ch_width_3);
  if ( data.roll < 118 ){
    leftPwm = 127 - map(data.roll, 0, 127, 0, 127);
    rightPwm = 0;
  }else if (data.roll > 133){
    rightPwm = map(data.roll, 127, 255, 0, 127);
    leftPwm = 0;
  } else {
    leftPwm = 0;
    rightPwm = 0;
  }
  analogWrite(5, leftPwm);
  analogWrite(6, rightPwm);
  digitalWrite(2, data.aux2);
  digitalWrite(3, LOW);
}
